import React, { useState,useEffect, useTransition } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input, Transfer,Descriptions } from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined,SearchOutlined  } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { listInci,delInci,addInci} from "@/api/modules/tspec2015";
import { list} from "@/api/modules/inci";
import { ProFormColumnsType } from '@ant-design/pro-components'
import { getInfo } from "@/api/login/ssoLogin";

const Children= ({ oldannex,oldserial,oldproduct }) => { 
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [transferDataSource, setTransferDataSource] = useState([]);  
  const [targetKeys, setTargetKeys] = useState([]);  
  const [onReloadNum,setOnReloadNum] = useState(null)
  
  const [viewStatus, setViewStatus] = useState(false); // 加载状态 


  // 使用useEffect在组件挂载时获取数据  
  useEffect(() => {  
    getInfo().then(res=>{
      console.log(res,'res')
      let data = res.data
      data.roles.forEach((item)=>{
        if(item == "Formulator"){
          setViewStatus(true)
        }
      })
    }) 

  }, []);

   const getQueryVariable = (variable) =>{
    const query = window.location.search.substring(1);
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
  }

  const options = [  
    { label: t('Option 1'), value: '1' },  
    { label: t('Option 2'), value: '2' },  
    // ... 其他选项  
  ];
  const formColumns:ProFormColumnsType[] = [{
    title: t('INCI'),
    dataIndex: 'search',
    valueType: 'text', 
  },  ]

  const columns: any = [
    {
      title: t('ing.lawInciSerial'),
      dataIndex: 'lawInciSerial',
      key: 'lawInciSerial',
      width: 60,
      fixed:'left',
    },
    {
      title: t('ing.inciCn'),
      dataIndex: ['inci','inciCn'],
      width: 100,
      key: 'inciCn',
    },
    {
      title: t('ing.inciUs'),
      dataIndex:  ['inci','inciUs'],
      width: 120,
      key: 'inciUs',
    },
    {
      title: t('ing.inciEu'),
      dataIndex: ['inci','inciEu'],
      width:120,
      key: 'inciEu',
    },
    {
      title: t('cas'),
      dataIndex:  ['inci','cas'],
      key: 'cas',
    },
    {
      title: t('source'),
      dataIndex: ['inci','source'],
      key: 'source',
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
         
          {viewStatus ? null : (
            <>
               <Button type="link" danger onClick={() => handleDelete(record.id)}>  
                {t('delete')}   
                </Button>  
            </>
          )}
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const annex  = oldannex
    const serial  =  oldserial
    if(serial){
        formData.serial = decodeURI(serial.toString())
        formData.eq=1;
        formData.annex=decodeURI(annex.toString())
    }
    const { success, data} = await listInci({...formData, orderby: 'a.id', order: 0})
    if(!success) return false
    console.log(data)
    const list2 = data.data.page
    return {
      data: list2,
      total: data.data.total
    }
  } 

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    let serial=oldserial
    let annex=oldannex
      // 获取右边穿梭框的值  
      const selectedKeys = targetKeys;  
      //调用接口
      addInci(decodeURI(serial.toString()),decodeURI(annex.toString()),selectedKeys).then(res=>{
        message.success("Success")
        // 清空表单  
        form.resetFields();  
        // 清空穿梭框数据（可选）  
        setTargetKeys([]); 
        setIsModalVisible(false)
        setOnReloadNum(Date.now())
      })

    // ...处理接口响应...  

  };  

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delInci(inciIds).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
        }) 
      },  
    }); 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const handleSearch = async (values) => {  
    const { inci } = values;  
    let columns = []
    const param = {limit:20,page:1,search:inci,order:1,offeset:0}
    // 调用接口获取数据  
    list(param).then(res=>{
        let data = res.data.data.page
        data.map(item=>{
            columns.push({
                title:item.inciCn,
                key:item.serial,
            })
        })
        setTransferDataSource(columns)
    })

    // const data = result.data;  
    // setTransferDataSource(data);  
  };  
  
  const handleTransferChange = (nextTargetKeys, direction, moveKeys) => {  
    setTargetKeys(nextTargetKeys);  
  };  

  const renderOperator = <>
    <Button disabled={viewStatus} type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
  </>
  
  return (
    <div> 
    <div style={{marginBottom:'2%'}}>
    <Descriptions bordered layout="vertical">  
      <Descriptions.Item label={t('tspec2015.annex')}>  
        {oldannex}  
      </Descriptions.Item>  
      <Descriptions.Item label={t('tspec2015.serial')}>  
        {oldserial}  
      </Descriptions.Item>  
      <Descriptions.Item label={t('tspec2015.productTypeBodyPart')}>  
        {oldproduct}  
      </Descriptions.Item>  
      
    </Descriptions>  
    </div>
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form}  layout="vertical">  
          <Form.Item  
            name="inci"  
            label={t('INCI')}
          >  
            <Input.Search  
              enterButton  
              placeholder="请输入INCI进行搜索"  
              onSearch={() => form.validateFields().then(handleSearch)}  
              suffix={<SearchOutlined />}  
            />  
          </Form.Item>  
          <Form.Item>  
            <Transfer  
              dataSource={transferDataSource}  
              titles={['未选/Unselected', '已选/Selected']}  
              targetKeys={targetKeys}  
              onChange={handleTransferChange}  
              render={item => item.title}  
            />  
          </Form.Item>  
        </Form>
        </Modal>  
    </div>
  )
}
export default Children
